<!--
 * @Descripttion: 多规格的组件
 * @version:
 * @Author: cxguo
 * @Date: 2019-10-30 21:29:17
 * @LastEditors: cxguo
 * @LastEditTime: 2019-12-13 15:14:09
 -->
<template>
  <div>
    <div class="clearfix">
      <h3 class="fl">多规格</h3>
      <el-checkbox v-model="multi.specs" class="fl margin-l10" style="margin-top:-3px;" size="mini" border>多规格</el-checkbox>
      <el-button class="fr" type="text" @click="btnSetupSpecs">规格设置</el-button>
    </div>
    <el-divider />
    <!-- specsData: {{ specsData }} <br>
    unitData: {{ unitData }} <br>
    selectSpecsData: {{ selectSpecsData }} -->
    <el-form
      ref="goodInfoForm"
      :model="dataObj"
      :label-position="'left'"
      label-width="60px"
      size="small"
      class="w400"
    >
      <el-form-item v-for="(specsObj,index) in specsData" :key="`${index}`" :label="`${specsObj.label}: `">
        <el-checkbox-group v-model="specsObj.valueData">
          <el-checkbox v-for="(checklabel, cindex) in specsObj.data " :key="`${cindex}`" :label="checklabel" />
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <vxe-grid
      ref="table"
      class="grid"
      border
      size="small"
      resizable
      highlight-hover-row
      :edit-config="{trigger: 'click', mode: 'row'}"
      :columns="columnsData"
      :data="finalTableData"
    />
  </div>

</template>
<script>
import { oftenuse } from '@/libs/mixins'
import clonedeep from 'clonedeep'
import { DialogPrice } from './components'
import { specs } from './mixins'
import { getData } from '@/api/goods/goods-temp.js'
import { genGoodSkuCode } from '@/api/goods/goods-sku.js'
import Vue from 'vue'

export default {
  name: 'GoodSpecs',
  mixins: [oftenuse, specs],
  props: {
    multi: {
      type: Object,
      default: () => { return null }
    },
    baseData: {
      type: Object,
      default: () => { return null }
    },
    unitData: {
      type: Array,
      default: () => { return null }
    }
  },
  data() {
    return {
      specsData: [],
      originColumnsData: [
        { field: 'code',
          title: '商品编码',
          editRender: { name: 'ElInput', props: { size: 'mini' }}
        },
        { field: 'name',
          title: '商品名称',
          editRender: { name: 'ElInput', props: { size: 'mini' }}
        }
      ],
      finalTableData: [],
      skuCode: ''
    }
  },
  computed: {
    /**
     * 显示的列数据
     */
    columnsData: function() {
      const originColumnsData = this.originColumnsData
      const specsColumns = this.specsColumns
      return [...specsColumns, ...originColumnsData]
    },
    /**
     * 最终表格的数据
     */
    _finalTableData() {
      const spTableData = clonedeep(this.spTableData)
      spTableData.forEach((item, index) => {
        item.name = this.getGoodName(item)
        item.code = this.getOneSkuCode(this.skuCode, index)
        item.barcode = null
      })
      return spTableData
    },
    /**
     * 选中的规格
     */
    selectSpecsData: function() {
      const specsData = this.specsData
      const hasValueSpecs = specsData.filter(item => { return item.valueData && item.valueData.length > 0 })
      const result = []
      hasValueSpecs.forEach(item => {
        const obj = {}
        obj[item.label] = item.valueData
        result.push(obj)
      })
      return result
    }
  },
  watch: {
    '_finalTableData': {
      handler(data) {
        this.finalTableData = data
      }
    }
  },
  created() {
    this.getSkuCode()
    this.getSpecsSelectData()
  },
  methods: {
    btnSetupSpecs() {
      this.$router.push({ name: 'specsManager' })
    },
    btnPrice() {
      const Class = Vue.extend(DialogPrice)
      const unitData = this.unitData || []
      const props = {
        unitData
      }
      let instance = Object.assign(new Class(), props)
      instance = instance.$mount()
      document.body.appendChild(instance.$el)
    },
    // api
    /**
     * 最终表格里所有的数据
     */
    getSpTableData() {
      return this.$refs.table.getTableData().fullData
    },
    valiData() {
      const selectSpecsData = this.selectSpecsData
      const that = this
      return new Promise((resolve, reject) => {
        if (selectSpecsData.length) {
          debugger
          resolve()
        } else {
          const MSG = '至少选择一个规格！'
          that.$message.error(MSG)
          reject(new Error(MSG))
        }
      })
    },
    getGoodName(specsRow) {
      let goodName = this.baseData.name
      Object.keys(specsRow).forEach((key, index) => {
        goodName += `-${specsRow[key]}`
      })
      return goodName
    },
    /**
     * 获取Sku编码
     */
    getSkuCode() {
      genGoodSkuCode().then(res => {
        console.log('获取code', res.data.data)
        if (!res.data.flag) return this.$message.error('获取sku编码失败！')
        this.skuCode = res.data.data
      })
    },
    getOneSkuCode(initCode, index) {
      const initCodeNum = initCode.match(/\d+/g).join('')
      const perfix = initCode.replace(initCodeNum, '')
      return `${perfix}${Number(initCodeNum) + index}`
    },
    /**
     * 获取规格待选数据
     */
    getSpecsSelectData() {
      getData({ tempId: '1' }).then(res => {
        if (res.data.flag) {
          const data = res.data.data[0]
          const spData = JSON.parse(data.specs)
          spData.forEach(item => {
            item.valueData = []
          })
          this.specsData = spData
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .el-divider--horizontal{
    margin: 5px 0;
  }
</style>
